<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<title>购物车</title>

<style>
table{
border-collapse: collapse;
}

thead>tr{
border-bottom:2px solid #B7D1FB ;
}

tbody>tr{
border-bottom:1px solid #B7D1FB; 
}

th,
td{
padding: 12px;
}

a{
text-decoration: none;
}
</style>
</head>
<body>
<h3>我的购物车</h3>
<table>
<thead>
<tr>
	<th>
		<input type="checkbox" id="allcb" class="checkall" />
		<label for="allcb">全选</label>
	</th>
	<th>商品</th>
	<th>单价</th>
	<th>数量</th>
	<th>小计</th>
	<th>操作</th>
</tr>
</thead><!-- 表头 -->
<tr>
<td>
	<input class='checkgood' type="checkbox" name="c" />
</td>

<td class="goodname">JavaScript实战</td>
<td class="price">45.8</td>
<td>
	<button>-</button>
	<span class='num'>1</span>
	<button>+</button>
</td>
<td style="color: red;" class="sum">45.8</td>
<td>
	<a href="#">删除</a>
</td>
</tr>
<tr>
<td>
	<input class='checkgood' type="checkbox" name="c" />
</td>

<td class="goodname">JavaScript实战</td>
<td class="price">45.8</td>
<td>
	<button>-</button>
	<span class='num'>1</span>
	<button>+</button>
</td>
<td style="color: red;" class="sum">45.8</td>
<td>
	<a href="#">删除</a>
</td>
</tr>
<tr>
<td id="order" colspan="6" style="text-align: right;">
	<span class="totalnum">16</span>件商品总计
	<span class="totalprice" style="color: red; font-size: 22px;">0</span>
	<a href="#" style="border-radius: 4px;
	padding: 8px; background: #F08B34; color: #fff;">提交订单</a>
</td>
</tr>
</table>
<script>
	//入口函数
	$(function(){
	
		$('td>button').click(function(){
			let opt=$(this).text();
			let num=Number($(this).siblings('.num').text());
			num=eval(num+opt+1)<0 ? 0:eval(num+opt+1);
			$(this).siblings('.num').text(num);
			getSum($(this).parent().parent())
		
		})
		function getSum(tr){
			let price=Number(tr.find('.price').text());
			let num=Number(tr.find('.num').text());
			// console.log(price+""+num);
			let sum=(price*num).toFixed(2);
			// console.log(sum);
			tr.find('.sum').text(sum);
			getAllSum()
		}
		function getAllSum(){
			let allChooseTr=$('.checkgood:checked').parent().parent()
			// console.log(allChooseTr);
			let allNumSpan=allChooseTr.find('.num');
			let allSumTd=allChooseTr.find('.sum');
			//总价
			let totalNum=0;
			let totalPrice=0;
			allNumSpan.each(function(){
				totalNum+=Number($(this).text())
			})
			allSumTd.each(function(){
				totalPrice+=Number($(this).text())
			})
			
			// console.log(totalNum+" "+totalPrice)
			$('.totalnum').text(totalNum);
			$('.totalprice').text(totalPrice.toFixed(2));
				
		}
		
		$('.checkgood').click(getAllSum)
		$('.checkall').click(function(){
			let k=$(this).prop('checked');
			$('.checkgood').prop('checked',k);
			
			getAllSum();
		})
		
			
			
	})
	
</script>
</body>
</html>
